package com.theyeasy.dvmini.pc.controller;

import java.io.IOException;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.testng.util.Strings;
import org.theyeasy.weixin.util.WxMiniUtil;

import com.alibaba.fastjson.JSONObject;
import com.theyeasy.dvmini.enums.ChatLogReplyType;
import com.theyeasy.dvmini.model.Sales;
import com.theyeasy.dvmini.model.WebSockMsg;
import com.theyeasy.dvmini.service.ChatLogService;
import com.theyeasy.dvmini.service.DvminiSocketService;
import com.theyeasy.dvmini.service.FansService;
import com.theyeasy.dvmini.service.PosterService;
import com.theyeasy.dvmini.service.SalesService;
import com.theyeasy.dvmini.vo.Vo_msg;

@Controller
@RequestMapping("/sale")
public class SalesController extends BaseController {

	@Autowired
	SalesService saleService;

	@Autowired
	PosterService posterService;

	@Autowired
	DvminiSocketService dvminiSocketService;

	@RequestMapping("/saleIndex")
	public ModelAndView salesIndex() {
		ModelAndView mv = new ModelAndView("/pc/sale/sale");
		return mv;
	}

	// 销售人员列表
	@RequestMapping(value = "/getSalesList")
	@ResponseBody
	public Object salesList(Integer page, Integer pagesize, String keyword, Integer projectid, Boolean isvanker) {
		// Boolean isvanker
		return new Vo_msg(0, saleService.getSalesList(page, pagesize, keyword, projectid, isvanker));
	}

	// 添加销售
	@RequestMapping(value = "/addsales")
	@ResponseBody
	public Object addsales(String name, String phone, Integer projectid, Boolean isValid, Boolean isVanker) {
		String result = saleService.addSales(name, phone, projectid, isValid, isVanker);
		if (result.equals("ok")) {
			return new Vo_msg(0, null, "添加成功");
		} else {
			return new Vo_msg(-1, null, result);
		}
	}

	// 修改销售
	@RequestMapping(value = "/updatesales")
	@ResponseBody
	public Object updatesales(Integer id, String name, String phone, Integer projectid, Boolean isValid,
			Boolean isVanker) {
		String result = saleService.updateSales(id, name, phone, projectid, isValid, isVanker);
		if (result.equals("ok")) {
			return new Vo_msg(0, "修改成功");
		} else {
			return new Vo_msg(-1, result);
		}
	}

	// 删除销售
	@RequestMapping(value = "/deletesales")
	@ResponseBody
	public Object deletesales(Integer id) {
		String result = saleService.deleteSales(id);
		if (result.equals("ok")) {
			return new Vo_msg(0, "删除成功");
		} else {
			return new Vo_msg(-1, result);
		}
	}

	// 获取
	@RequestMapping(value = "/getSales")
	@ResponseBody
	public Object getSales(Integer id) {
		Sales sale = saleService.getSales(id);
		if (sale != null) {
			return new Vo_msg(0, sale);
		} else {
			return new Vo_msg(-1, "获取失败，数据为空");
		}
	}

	// 导入
	@RequestMapping(value = "/ExcelSales")
	@ResponseBody
	public Object ExcelSales(MultipartFile file) {
		System.out.println("excel import begin");
		if (file == null || file.isEmpty())
			return new Vo_msg(-1, "导入失败，文件不能为空");
		String originalFilename = file.getOriginalFilename();

		String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);

		String result = "";
		try {
			result = saleService.ExcelSales(suffix, file.getInputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}

		if (result.startsWith("ok")) {
			return new Vo_msg(0, result);
		} else {
			return new Vo_msg(-1, "导入失败，数据异常");
		}
	}

	@RequestMapping(value = "/regist")
	public ModelAndView regist(Map<String, Object> model) {
		ModelAndView view = new ModelAndView("/pc/sale/regist", model);
		return view;
	}

	@Autowired
	ChatLogService chatLogService;

	@RequestMapping(value = "/test")
	@ResponseBody
	public Object test() {
		return WxMiniUtil.sendCustoMiniprogrampage("oB3300KmPWcLZ1Xhc7heqHQBbKEc", "首页",
				"/pages/floorlistCopy2/floorlistCopy2",
				"http://mini.weiyisz.com/res/upload/posttemplet/20171120172538_496.jpg",
				"HNRJmkZmfmdxGAAE4r9-yWs2ojKRdLyt5MSPpO_9sTWO4XKHzYrG30z1RJ0uXxlk");
	}

	@RequestMapping(value = "/chatlogList")
	@ResponseBody
	public Object chatLogList(HttpServletRequest request, HttpServletResponse response,
			@RequestParam("salesId") Integer salesId,
			@RequestParam(value = "fansId", defaultValue = "-1", required = false) Integer fansId,
			@RequestParam("page") Integer page) {
		return chatLogService.getChatLogListBySalesId(salesId, fansId, page);
	}

	@RequestMapping(value = "/cleanCatlogList")
	@ResponseBody
	public Object cleanCache(@RequestParam("salesId") Integer salesId, @RequestParam("fansId") Integer fansId) {
		WebSockMsg msg = new WebSockMsg();
		msg.setFansid(fansId);
		msg.setSalesid(salesId);
		dvminiSocketService.cleanCache(msg, true);
		return new Vo_msg(0, true);
	}

	@RequestMapping(value = "/checkChatStatus")
	@ResponseBody
	public boolean checkChatStatus(@RequestParam("salesId") Integer salesId, @RequestParam("fansId") Integer fansId) {
		return dvminiSocketService.checkChatStatus(salesId, fansId);
	}

	@RequestMapping(value = "/checkoutStatus")
	@ResponseBody
	public boolean checkoutStatus(@RequestParam("salesId") Integer salesId, @RequestParam("fansId") Integer fansId) {
		if (dvminiSocketService.checkChatStatus(salesId, fansId)) {
			dvminiSocketService.removeChatStatus(salesId, fansId);
			return false;
		} else {
			dvminiSocketService.updateChatStatus(salesId, fansId);
			new Thread(new Runnable() {

				@Override
				public void run() {
					try {
						WebSockMsg msg = new WebSockMsg();
						msg.setSalesid(salesId);
						msg.setFansid(fansId);
						msg.setAskfrom(1);
						msg.setAsktime(new Date());
						Sales sales = saleService.getSales(salesId);
						boolean nullOrEmpty = Strings.isNullOrEmpty(sales.getName());
						String reply = nullOrEmpty ? "万小二" : sales.getName();
						msg.setReply("亲，下面是客服【" + reply + "】为您服务，万小二先退了[咖啡][咖啡]");
						msg.setReadTime(new Date());
						msg.setReplytype(ChatLogReplyType.自动回复.getIndex());
						msg.setReaded(true);
						msg.setNoticetime(new Date());
						dvminiSocketService.recevice(msg);
					} catch (Exception e) {

					}
				}
			}).start();

			return true;
		}
	}

	@RequestMapping(value = "/transferSales2Sales", method = RequestMethod.POST)
	@ResponseBody
	public Object transferSales2Sales(@RequestParam("oldSalesId") Integer oldSalesId,
			@RequestParam("salesId") Integer salesId, @RequestParam("fansId") Integer fansId) {
		try {
			saleService.transferSales2Sales(oldSalesId, salesId, fansId);
			return new Vo_msg(0, true);
		} catch (Exception e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		}
		return new Vo_msg(-1, false);
	}

	@RequestMapping(value = "/sendProudct", method = RequestMethod.GET)
	@ResponseBody
	public Object sendProudct(@RequestParam("productId") Integer projectid, @RequestParam("fansId") Integer fansId) {
		try {
			String sendProudct = saleService.sendProudct(projectid, fansId);
			JSONObject json = JSONObject.parseObject(sendProudct);
			Integer integer = json.getInteger("errcode");
			return new Vo_msg(integer, null);
		} catch (Exception e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		}
		return new Vo_msg(-1, false);
	}

}
